package com.taillive.commons;



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;


public class WebUtils {
    /**
     *   Check if a specified file name is a URL file name
     *   @param fileName The file name to be checked.
     */
    public static boolean isURLFile(String fileName) {
        String http = "http://";
        if (fileName == null || fileName.equals("")) {
            return false;
        }
        else {
            fileName = fileName.toLowerCase();
            if (fileName.indexOf(http) == 0) {
                //here we need to consider an intranet unc path, http://webserver/ is not an URL path.
                fileName = fileName.substring(http.length());

                int slashIndex = fileName.indexOf("/");
                if (slashIndex >= 0) {
                    //get the string section between 'http://' and the first slash '/'
                    fileName = fileName.substring(0, slashIndex);

                    if (fileName.indexOf(".") > 0) {
                        return true;
                    }
                    else {
                        return false; // it's an intranet unc path.
                    }

                }

                return true;
            }
            return false;
        }
    }



 
 	/**
   	*   Convert http url, escape function.. In http parameters, a '&' leading parameter, 
   	*   should not contains some special characters, so need to be convert to hex texts with a leading %
   	*   @param paraStr Parameter string
   	*   @return a converted http url
   	*/
   
  	public static String escape(String url){
  		if (url==null || url.equals(""))
  			return "";
  		
  		StringBuffer buf	=new StringBuffer();
  		for (int i=0; i<url.length(); i++){
  			char c	=url.charAt(i);
  			if (c=='%')
  				buf.append("%25");
  			else if (c=='?')
  				buf.append("%3F");
  			else if (c=='=')
  				buf.append("%3D");
  			else if (c=='&')
  				buf.append("%26");
  			else if (c==' ')
  				buf.append("%20");
  			else if (c=='\'')
  				buf.append("%27");
  			else if (c=='\"')
  				buf.append("%22");
  			else if (c==',')
  				buf.append("%2C");
  			else if (c=='<')
  				buf.append("%3C");
  			else if (c=='>')
  				buf.append("%3E");
  			else
  				buf.append(c);
  		}
  		
  		return buf.toString();
  	}
  
	

  	
  	/**
   	*   Convert back from escaped http url, unescape function.. 
   	*   @return a unescaped http url
   	*/
  	
  	public static String unescape(String url){
  		if (url==null || url.equals(""))
  			return "";
  		
  		StringBuffer buf	=new StringBuffer();
  		int i=0;
  		int len	=url.length();
  		while (i<len){
  			
  			if (i<len-2){
  				String s	=url.substring(i,i+3);
  				boolean foundEsc	=true;
  				
  				if ("%25".equals(s)){
  					buf.append("%");

  				}else if ("%26".equals(s)){
  					buf.append("&");

  				}else if ("%20".equals(s)){
  					buf.append(" ");

  				}else if ("%27".equals(s)){
  					buf.append("'");
  				
  				}else if ("%22".equals(s)){
  					buf.append("\"");

  				}else if ("%2C".equals(s)){
  					buf.append(",");

  				}else if ("%3C".equals(s)){
  					buf.append("<");

  				}else if ("%3E".equals(s)){
  					buf.append(">");
  				
  				}else{
  					foundEsc	=false;
  				}
  				
  				if (foundEsc){
  					i	+=3;
  				}else{
  					buf.append(url.charAt(i));
  					i++;
  				}
  			}else{
  				buf.append(url.charAt(i));
  				i++;
  			}
  		}
  		
  		return buf.toString();
  	}
  	
  
  
    /**
     * Read url text
     * @param url
     * @return
     */
    public static String readURLText(String url){
    	try{
    		URL u = new URL(url);
    		BufferedReader in = new BufferedReader(
    				new InputStreamReader(
    				u.openStream()));

    		String inputLine;
    		StringBuffer buf	=new StringBuffer();
    		while ((inputLine = in.readLine()) != null){
    			buf.append(inputLine);
    			buf.append("\n");
    		}

    		in.close();    	
    	
    		return buf.toString();
    	}catch(Exception e){
    		e.printStackTrace();
    		return "";
    	}
    	
    }  
    
    
    public static String filterHTML(String input) {
    	if(input==null){
    		return "";
    	}
    	
        StringBuffer filtered = new StringBuffer(input.length());
        char c;
        for (int i = 0; i < input.length(); i++) {
            c = input.charAt(i);
            if (c == '<') {
                filtered.append("&lt;");
            } else if (c == '>') {
                filtered.append("&gt;");
            } else if (c == '"') {
                filtered.append("&quot;");
            } else if (c == '&') {
                filtered.append("&amp;");
            } else {
                filtered.append(c);
            }
        }
        return (filtered.toString());
    }
    
    public static String getHtml(String s){
    	if(s==null){
			return "";
		}else{
			return s.replaceAll("\n", "<br>");
		}
    }
    
    public static String getFiltedHtml(String s){
    	if(s==null){
			return "";
		}else{
			return filterHTML(s).replaceAll("\n", "<br>");
		}
    }
    

    public static String convertLine(String input){
    	if(input==null||"".equals(input)){
    		return "";
    	}
    		
    	
        StringBuffer filtered = new StringBuffer(input.length());
        char c;
        for (int i = 0; i < input.length(); i++) {
            c = input.charAt(i);
            if (c == '\n') {
                filtered.append("<br>");
            } else {
                filtered.append(c);
            }
        }
        return (filtered.toString());
    }
    
	public static String escapeAll(String src) {
		int i;
		char j;
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length() * 6);

		for (i = 0; i < src.length(); i++) {

			j = src.charAt(i);

			if (Character.isDigit(j) || Character.isLowerCase(j)
					|| Character.isUpperCase(j))
				tmp.append(j);
			else if (j < 256) {
				tmp.append("%");
				if (j < 16)
					tmp.append("0");
				tmp.append(Integer.toString(j, 16));
			} else {
				tmp.append("%u");
				tmp.append(Integer.toString(j, 16));
			}
		}
		return tmp.toString();
	}

	public static String unescapeAll(String src) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(src
							.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(src
							.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

}
